package main

import (
    "net"
    "strings"
)

type User struct{
    Name string
    Addr string
    C    chan string
    conn net.Conn
    server *Server
}

//创建用户接口
func NewUser(conn net.Conn, server *Server) *User {
    addr := conn.RemoteAddr().String()
    user := &User{
        Name:addr,
        Addr:addr,
        C   : make(chan string),
        conn:conn,
        server:server,
    }

    //监听当前user channel消息的goroutine
    go user.ListenerMessage()

    return user
}

//在线处理
func (this *User) Online(){
    //用户上线，将用户放入OnlineMap
    this.server.mapLock.Lock()
    this.server.OnlineMap[this.Name] = this
    this.server.mapLock.Unlock()

    //广播当前用户上线消息
    this.server.BroadCast(this,"已上线")
}

//下线处理
func (this *User) Offline(){
    //用户下线，将用户从OnlineMap删除
    this.server.mapLock.Lock()
    delete(this.server.OnlineMap,this.Name)
    this.server.mapLock.Unlock()

    //广播当前用户下线消息
    this.server.BroadCast(this,"下线")
}

func (this *User) SendMsg(msg string){
    this.conn.Write([]byte(msg))
}

//将得到的消息进行广播
func (this *User) DoMessage(msg string){
    if msg == "who" {
        //查询当前在线用户
        this.server.mapLock.Lock()
        for _, user := range this.server.OnlineMap {
            if(user != this){
                onlineMsg := "[" + user.Addr + "]" + user.Name + ":在线...\n"
                this.SendMsg(onlineMsg)
            }
        }
        this.server.mapLock.Unlock()
    }else if len(msg) > 7 && msg[:7] == "rename|" {
        //修改用户名格式 rename|用户名
        newName := strings.Split(msg,"|")[1]
        //判断用户名是否存在
        _, ok := this.server.OnlineMap[newName]
        if ok {
            this.SendMsg("用户名已存在\n")
        }else{
            this.server.mapLock.Lock()

            delete(this.server.OnlineMap,this.Name)
            this.Name = newName
            this.server.OnlineMap[newName] = this

            this.server.mapLock.Unlock()
            this.SendMsg("更新用户名：" + this.Name + ",成功\n")
        }
    }else if len(msg) > 4 && msg[:3] == "to|" {
        //消息格式 to|cxhblog|Hello World!
        remoteName := strings.Split(msg,"|")[1]
        if remoteName == "" {
            this.SendMsg("消息格式错误\n")
            return
        }

        //根据用户名，得到User对象
        remoteUser, ok := this.server.OnlineMap[remoteName]
        if !ok {
            this.SendMsg("用户不存在\n")
            return
        }

        //获取消息内容，发送消息
        text := strings.Split(msg,"|")[2]
        if text == "" {
            this.SendMsg("消息内容为空，请重新发送\n")
            return
        }

        remoteUser.SendMsg(this.Name + ",对你说:" + text + "\n")
    }else{
        this.server.BroadCast(this,msg)
    }
}

//监听User channel，有消息就发给客户端
func (this *User) ListenerMessage(){
    for{
        msg := <-this.C
        this.conn.Write([]byte(msg + "\n"))
    }
}